<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      
      <el-form-item label="部门" prop="orgId">
        <el-select v-model="queryParams.orgId" placeholder="请选择部门" clearable size="small" style="width: 200px">
          <el-option
            v-for="dept in deptTreeOptions"
            :key="dept.deptId"
            :label="dept.label"
            :value="dept.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="提交用户" prop="user">
        <el-input
          v-model="queryParams.user"
          placeholder="请输入提交用户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 120px">
          <el-option label="启用" value="0" />
          <el-option label="禁用" value="1" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="文件列表" prop="fileId">
        <el-input
          v-model="queryParams.fileId"
          placeholder="请输入文件列表"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:deatil:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:deatil:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:deatil:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:deatil:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deatilList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据ID" align="center" prop="id" />
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column label="部门" align="center" prop="orgId">
        <template slot-scope="scope">
          {{ getDeptName(scope.row.orgId) }}
        </template>
      </el-table-column>
      <el-table-column label="提交用户" align="center" prop="user" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
            {{ scope.row.status === '0' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
    
      <el-table-column label="文件列表" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.fileList && scope.row.fileList.length > 0">
            <div v-for="(file, index) in scope.row.fileList" :key="index">
              <a :href="file.filePath" target="_blank">{{ file.fileName }}</a>
            </div>
          </div>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:deatil:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:deatil:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:deatil:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="isDetailMode">
        <el-form-item label="内容" prop="content">
          <editor v-model="form.content" :min-height="192" :disabled="isDetailMode"/>
        </el-form-item>
        
        <el-form-item label="部门" prop="orgId">
          <el-select 
            v-model="form.orgId" 
            placeholder="请选择部门" 
            style="width: 100%"
            :disabled="isDetailMode"
            :clearable="!isDetailMode"
          >
            <el-option
              v-for="dept in deptTreeOptions"
              :key="dept.deptId"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </el-form-item>
    
        <el-form-item label="提交用户" prop="user">
          <el-input 
            v-model="form.user" 
            placeholder="请输入提交用户" 
            :disabled="isDetailMode"
            :readonly="isDetailMode"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select 
            v-model="form.status" 
            placeholder="请选择状态" 
            style="width: 100%"
            :disabled="isDetailMode"
            :clearable="!isDetailMode"
          >
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
     
        <el-form-item label="附件" v-if="!isDetailMode">
          <el-upload
            ref="upload"
            class="upload-demo"
            action="/dev-api/system/file/upload"
            :limit="5"
            :file-list="form.fileList"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单个文件不超过100MB，最多上传5个文件</div>
          </el-upload>
        </el-form-item>
        
        <!-- 详情模式下的附件显示 -->
        <el-form-item label="附件" v-if="isDetailMode">
          <div v-if="form.fileList && form.fileList.length > 0">
            <div v-for="(file, index) in form.fileList" :key="index">
              <a :href="file.url" target="_blank">{{ file.name }}</a>
            </div>
          </div>
          <span v-else>无附件</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isDetailMode" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeatil, getDeatil, delDeatil, addDeatil, updateDeatil, exportDeatilWithFiles } from "@/api/deatil/deatil";
import { listDept } from "@/api/system/dept";

export default {
  name: "Deatil",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务列表表格数据
      deatilList: [],
      // 部门选项
      deptTreeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: null,
        orgId: null,
        user: null,
        status: null,
        fileId: null
      },
      // 表单参数
      form: {
        id: null,
        content: null,
        orgId: null,
        user: null,
        fileList: [],
        createTime: null,
        updateTime: null,
        status: "0"
      },
      // 是否详情模式
      isDetailMode: false,
      // 表单校验
      rules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        orgId: [
          { required: true, message: "部门不能为空", trigger: "change" }
        ],
        user: [
          { required: true, message: "提交用户不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDeptList();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptList() {
      listDept().then(response => {
        this.deptTreeOptions = this.handleDeptOptions(response.data);
      });
    },
    // 处理部门数据
    handleDeptOptions(depts) {
      const deptMap = {};
      depts.forEach(dept => {
        deptMap[dept.deptId] = dept;
      });
      const options = [];
      depts.forEach(dept => {
        let fullName = dept.deptName;
        let parentId = dept.parentId;
        while (parentId !== 0 && deptMap[parentId]) {
          const parent = deptMap[parentId];
          fullName = parent.deptName + '/' + fullName;
          parentId = parent.parentId;
        }
        const option = {
          deptId: dept.deptId, // 保持原始类型
          label: fullName,
          value: dept.deptId   // 保持原始类型，不进行parseInt转换
        };
        options.push(option);
      });
      options.sort((a, b) => a.label.localeCompare(b.label));
      return options;
    },
    // 获取部门名称
    getDeptName(orgId) {
      // 确保orgId类型匹配
      const dept = this.deptTreeOptions.find(item => item.deptId == orgId); // 使用==进行类型转换比较
      return dept ? dept.label : '';
    },
    /** 查询任务列表 */
    getList() {
      this.loading = true;
      listDeatil(this.queryParams).then(response => {
        this.deatilList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isDetailMode = false; // 重置详情模式
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        content: null,
        orgId: null,
        user: null,
        fileList: [],
        createTime: null,
        updateTime: null,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 手动重置查询参数
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        content: null,
        orgId: null,
        user: null,
        status: null,
        fileId: null
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 重置详情模式
      this.isDetailMode = false;
      this.reset();
      this.open = true;
      this.title = "添加任务列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 设置为编辑模式
      this.isDetailMode = false;
      this.reset();
      const id = row.id || this.ids
      getDeatil(id).then(response => {
        const data = response.data;
        
        // 保持orgId的原始类型，不进行转换
        const orgId = data.orgId;
        
        this.form = {
          ...data,
          orgId: orgId,
          // 确保status是字符串类型
          status: data.status ? String(data.status) : "0",
          fileList: (data.fileList || []).map(file => ({
            name: file.fileName,
            url: file.filePath
          }))
        };
        
        this.open = true;
        this.title = "修改任务列表";
      });
    },
    /** 详情查看操作 */
    handleDetail(row) {
      // 设置为详情模式
      this.isDetailMode = true;
      this.reset();
      const id = row.id;
      getDeatil(id).then(response => {
        const data = response.data;
        
        // 保持orgId的原始类型，不进行转换
        const orgId = data.orgId;
        
        this.form = {
          ...data,
          orgId: orgId,
          // 确保status是字符串类型
          status: data.status ? String(data.status) : "0",
          fileList: (data.fileList || []).map(file => ({
            name: file.fileName,
            url: file.filePath
          }))
        };
        
        this.open = true;
        this.title = "查看任务详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 获取上传组件的文件列表最新状态
          const uploadRef = this.$refs.upload;
          const currentFileList = uploadRef ? uploadRef.uploadFiles : [];
          
          // 处理文件列表数据
          const submitData = {
            ...this.form,
            fileList: currentFileList.map(file => ({
              fileName: file.name,
              filePath: file.response ? file.response.data.url : file.url
            }))
          };

          if (this.form.id != null) {
            updateDeatil(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeatil(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除任务列表编号为"' + ids + '"的数据项？').then(function() {
        return delDeatil(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 构建导出参数
      const exportParams = {
        ...this.queryParams
      };
      
      // 如果有选中的记录，只导出选中的
      if (this.ids && this.ids.length > 0) {
        exportParams.ids = this.ids.join(',');
      }
      
      // 调用导出接口
      exportDeatilWithFiles(exportParams).then(response => {
        // 创建下载链接
        const blob = new Blob([response], { type: 'application/zip' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `任务列表数据_${new Date().getTime()}.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
        this.$modal.msgSuccess("导出成功");
      }).catch(error => {
        this.$modal.msgError("导出失败：" + error.message);
      });
    },
    /** 文件上传相关方法 */
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!isLt100M) {
        this.$message.error('上传文件大小不能超过 100MB!');
        return false;
      }
      return true;
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 直接使用完整的文件列表更新
        this.form.fileList = fileList.map(item => ({
          name: item.name,
          url: item.response ? item.response.data.url : item.url
        }));
        this.$message.success('文件上传成功');
      } else {
        this.$message.error('文件上传失败');
      }
    },
    handleRemove(file, fileList) {
      const fileName = file.name;
      this.$http.delete(`/system/file/delete?fileName=${fileName}`).then(response => {
        if (response.data.code === 200) {
          // 直接使用完整的文件列表更新
          this.form.fileList = fileList.map(item => ({
            name: item.name,
            url: item.response ? item.response.data.url : item.url
          }));
          this.$message.success('文件删除成功');
        } else {
          this.$message.error('文件删除失败');
        }
      });
    }
  }
};
</script>
